package cn.yyh.servicePay.service.impl;

import cn.yyh.commons.constant.JobTypes;
import cn.yyh.commons.service.impl.MyBaseServiceImpl;
import cn.yyh.commons.utils.AlipayConfig;
import cn.yyh.commons.utils.BusinessConstant;
import cn.yyh.commons.utils.GetTokenUtil;
import cn.yyh.servicePay.client.AdoptOrderClient;
import cn.yyh.servicePay.client.ProductOrderClient;
import cn.yyh.servicePay.client.QuartzClient;
import cn.yyh.servicePay.domain.*;
import cn.yyh.servicePay.mapper.AlipayInfoMapper;
import cn.yyh.servicePay.mapper.PayBillMapper;
import cn.yyh.servicePay.mapper.PayFlowMapper;
import cn.yyh.servicePay.service.IPayBillService;
import cn.yyh.servicePay.utils.AliPayUtil;
import cn.yyh.servicePay.utils.ConvertUtils;
import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import org.csource.common.MyException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

@Service
public class PayBillServiceImpl extends MyBaseServiceImpl<PayBillMapper, PayBill> implements IPayBillService {

    @Autowired
    private AlipayInfoMapper alipayInfoMapper;

    @Autowired
    private PayBillMapper payBillMapper;

    @Autowired
    private PayFlowMapper payFlowMapper;
    @Autowired
    private AdoptOrderClient adoptOrderClient;
    @Autowired
    private QuartzClient quartzClient;
    @Autowired
    private ProductOrderClient productOrderClient;


    @Override
    public String pay(PayBill bill) throws MyException {
        if (bill == null
                || bill.getUnionPaySn() == null
                || bill.getMoney() == null
                || bill.getPayChannel() == null) {
            throw new MyException("相关参数不能为空!");
        }
        PayBill payBill = baseMapper.getById(bill.getId());
        if (payBill == null) {
            throw new MyException("没法找到相关订单!");
        }

        //0 余额 1 支付宝 2 微信 3 银联
        switch (payBill.getPayChannel().intValue()) {
            case 1:
                AlipayInfo info = alipayInfoMapper.loadByShopId(payBill.getShop_id());
                return AliPayUtil.pay(info, payBill);
            case 2:
                break;
            case 3:
                break;
            default:
                break;
        }
        return null;
    }

    @Override
    public void dealNotify(HttpServletRequest request) throws UnsupportedEncodingException, MyException, AlipayApiException {
        //获取支付宝POST过来反馈信息
        try {
            Map<String, String> params = new HashMap<String, String>();
            Map<String, String[]> requestParams = request.getParameterMap();
            for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
                String name = (String) iter.next();
                String[] values = (String[]) requestParams.get(name);
                String valueStr = "";
                for (int i = 0; i < values.length; i++) {
                    valueStr = (i == values.length - 1) ? valueStr + values[i]
                            : valueStr + values[i] + ",";
                }
                //乱码解决，这段代码在出现乱码时使用
                params.put(name, valueStr);
            }
            String unionPaySn = params.get("out_trade_no");
            PayBill bill = payBillMapper.loadByUnionPaySn(unionPaySn);
            if (bill != null) {
                AlipayInfo info = alipayInfoMapper.loadByShopId(bill.getShop_id());
                //验证签名
                boolean signVerified = AlipaySignature.rsaCheckV1(
                        params,
                        info.getAlipay_public_key(),
                        AlipayConfig.charset,
                        AlipayConfig.sign_type); //调用SDK验证签名
                if (signVerified) {//验证成功
                    //商户订单号
                    String out_trade_no = request.getParameter("out_trade_no");
                    //支付宝交易号
                    String trade_no = request.getParameter("trade_no");
                    //交易状态
                    String trade_status = request.getParameter("trade_status");

                    if ("TRADE_FINISHED".equals(trade_status)) {

                    } else if ("TRADE_SUCCESS".equals(trade_status)) {
                        //1.改支付单状态
                        bill.setState(1);
                        bill.setUpdateTime(new Date());
                        payBillMapper.update(bill);
                        //2.记录流水  自己去玩
                        //3.修改业务库的业务订单状态
                        PayFlow payFlow = new PayFlow();
                        BeanUtils.copyProperties(bill, payFlow);

                        switch (bill.getBusinessType()) {
                            case BusinessConstant.BUSINESS_TYPE_ADOPT:
                                payFlow.setBusinessName("宠物领养订单");
                                String byId = adoptOrderClient.getById(bill.getBusinessKey());
                                AdoptOrder order = ConvertUtils.toAdoptOrder(ConvertUtils.adoptOrder(byId));
                                order.setState(1);
                                adoptOrderClient.update(order);
                                quartzClient.deleteQuartz(JobTypes.PAY_OVER_TIME_ADOPT_ORDER+order.getId());
                                break;
                            case BusinessConstant.BUSINESS_TYPE_GOODS:
                                payFlow.setBusinessName("商品订单");
                                break;
                            case BusinessConstant.BUSINESS_TYPE_PRODUCT:
                                payFlow.setBusinessName("服务订单");
                                String client = productOrderClient.getById(bill.getBusinessKey());
                                ProductOrder productOrder = ConvertUtils.toProductOrder(ConvertUtils.productOrder(client));
                                productOrder.setState(1);
                                productOrderClient.update(productOrder);
                                quartzClient.deleteQuartz(JobTypes.PAY_OVER_TIME_PRODUCT_ORDER+productOrder.getId());
                                break;
                            case BusinessConstant.BUSINESS_TYPE_ACQUISITION:
                                payFlow.setBusinessName("寻宠收购订单");
                                break;
                            default:
                                break;
                        }
                        if (bill.getPayChannel() == 1) {
                            payFlow.setPayChannel(1);
                            payFlow.setPayChannelName("支付宝支付");
                        } else if (bill.getPayChannel() == 2) {
                            payFlow.setPayChannelName("微信支付");
                        } else if (bill.getPayChannel() == 3) {
                            payFlow.setPayChannelName("银联支付");
                        } else {
                            payFlow.setPayChannelName("余额支付");
                        }
                        payFlow.setUnionPaySeq(bill.getUnionPaySn());
                        payFlow.setNote(bill.getDigest() + ",相关用户支付流水");
                        payFlowMapper.save(payFlow);

                    }
                }
            }
        } catch (AlipayApiException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        //4.@TODO 支付成功之后取消定时任务
    }

    //payBill.setState(1);
//                payBill.setUpdateTime(new Date());
//                payBillMapper.update(payBill);
//
//    // 生成相关流水
//    PayFlow payFlow = initPayFlow(payBill);
//                payFlowMapper.save(payFlow);

}
